﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace StableDiffusionTools.Interop
{
    public static class User32
    {
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool DestroyIcon(IntPtr hIcon);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(IntPtr hWnd, WindowMessage msg, [MarshalAs(UnmanagedType.Bool)]bool wParam, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(IntPtr hWnd, WindowMessage msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);


        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(IntPtr hWnd, WindowMessage msg, int wParam, int lParam);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetScrollInfo(IntPtr hwnd, int fnBar, ref SCROLLINFO lpsi);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern int GetScrollPos(IntPtr hWnd, int nBar);
        [DllImport("user32.dll", SetLastError = true)]
        public static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

        public static Point GetScrollPos(IntPtr handle)
        {
            uint EM_GETSCROLLPOS = 0x0400 + 221;
            var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Point)));
            Marshal.StructureToPtr(new Point(), ptr, false);
            SendMessage(handle, EM_GETSCROLLPOS, IntPtr.Zero, ptr);
            var point = (Point)Marshal.PtrToStructure(ptr, typeof(Point));
            Marshal.FreeHGlobal(ptr);
            return point;
        }

        public static Point SetScrollPos(IntPtr handle, Point point)
        {
            uint EM_SETSCROLLPOS = 0x0400 + 222;
            var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Point)));
            Marshal.StructureToPtr(point, ptr, false);
            SendMessage(handle, EM_SETSCROLLPOS, IntPtr.Zero, ptr);
            Marshal.FreeHGlobal(ptr);
            return point;
        }

        public static void VerticalScrollPageBottom(IntPtr handle)
        {
            SendMessage(handle, WindowMessage.VerticalScroll, (IntPtr)User32Constants.SB_PAGEBOTTOM, IntPtr.Zero);
        }
    }
}
